package base.thread;

import java.util.concurrent.atomic.AtomicLong;

class AtomicAccount{
	AtomicLong balance;
	public AtomicAccount(long money){
		balance=new AtomicLong(money);
		System.out.println("total Money "+balance);
	}
	
	public void withdraw(long money,int delay){
		long oldvalue=balance.get();
		if(oldvalue>=money){
			try {
				Thread.sleep(delay);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(balance.compareAndSet(oldvalue, oldvalue-money)){
				System.out.println(Thread.currentThread().getName()+" withdraw "+money+" successful !"+balance);
			}else{
				System.out.println(Thread.currentThread().getName()+" thread concurrent,withdraw failed!"+balance);
			}
		}else{
			System.out.println(Thread.currentThread().getName()+"balance is not enough,withdraw failed!"+balance);
		}
	}
}

public class AtomicAccountTest extends  Thread{
	AtomicAccount account;
	int delay;
	public AtomicAccountTest(AtomicAccount cAccount,int delay){
		this.account=cAccount;
		this.delay=delay;
	}
	public void run(){
		account.withdraw(100, delay);
	}
	public static void main(String[] args) {
		AtomicAccount account=new AtomicAccount(100);
		AtomicAccountTest test1=new AtomicAccountTest(account, 1000);
		AtomicAccountTest test2=new AtomicAccountTest(account, 1000);
		test1.start();
		test2.start();
	}
}
